package com.hyc;

import cn.hutool.crypto.SecureUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.TreeMap;

public class SignUtil {
    public static String sign(TreeMap<String, Object> paramMap, String signKey) {
        Long timeStamp = StringUtils.isNotBlank(paramMap.get("timestamp").toString()) ? Long.valueOf(paramMap.get("timestamp").toString()) : null;
        if (timeStamp == null) {
            return null;
        }
        Long now = System.currentTimeMillis();
        // 时间差不大于5分钟
        if (Math.abs(now - timeStamp) > 5 * 60 * 1000) {
            return null;
        }

        StringBuilder query = new StringBuilder();
        boolean hasParam = false;
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            if (areNotEmpty(key, value)) {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }
                query.append(key).append("=").append(value);
            }
        }
        query.append("&key=").append(signKey);

        return SecureUtil.md5(query.toString()).toUpperCase();
    }

    private static boolean areNotEmpty(String... values) {
        boolean result = true;
        if (values == null || values.length == 0) {
            result = false;
        } else {
            for (String value : values) {
                result &= !StringUtils.isBlank(value);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        TreeMap<String, Object> param = new TreeMap<String, Object>();
        param.put("name", "hyc@qq.com");
        param.put("age", "30");
        param.put("app", "OA");
        param.put("timestamp", String.valueOf(System.currentTimeMillis()));

        System.out.println(sign(param, "123456"));
    }
}
